package com.yuandian.management.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.security.util.SecurityUtils;
import com.yuandian.constant.Constants;
import com.yuandian.management.mapper.AgentIpMapper;
import com.yuandian.management.service.IAgentIpService;
import com.yuandian.management.service.IAgentStatusInfoService;
import com.yuandian.management.service.IAgentTableService;
import com.yuandian.management.vo.AgentConfigManager;
import com.yuandian.management.vo.AgentIpPojo;
import com.yuandian.management.vo.AgentIpVo;
import com.yuandian.management.vo.AgentStatusInfoVo;
import com.yuandian.utils.DateTool;
import com.yuandian.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * <p>
 * agentip管理表 服务实现类
 * </p>
 *
 * @author fucx
 * @since 2021-01-27
 */
@Service
public class AgentIpServiceImpl extends ServiceImpl<AgentIpMapper, AgentIpPojo> implements IAgentIpService {
	@Autowired
    private AgentIpMapper agentIpMapper;

	@Lazy
	@Autowired
    private IAgentStatusInfoService agentStatusInfoService;

    @Autowired
    private IAgentTableService agentTableService;

    /**
     * 查询所有ip
     * 
     * @return
     */
    @Override
    public List<AgentIpPojo> queryListAll() {
        return agentIpMapper.queryListAll();
    }

    /**
     * 查询所有状态正常agent ip信息
     * 
     * @return
     */
    @Override
    public List<AgentIpVo> queryList(String searchKey) {
        List<AgentIpVo> voList = new ArrayList<AgentIpVo>();
//        String zeroToday = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        List<AgentIpPojo> list = agentIpMapper.queryList(searchKey, null);
        if (!CollectionUtils.isEmpty(list)) {
            for (AgentIpPojo po : list) {
                AgentIpVo vo = new AgentIpVo();
                BeanUtils.copyProperties(po, vo);

                voList.add(vo);
            }
        }

        return voList;
    }

    /**
     * 插入AgentIp
     * 
     * @param agentIp
     */
    @Override
    public void insertAgentIp(AgentIpPojo agentIp) {
        agentIpMapper.insertAgentIp(agentIp);
    }

    /**
     * 根据id更新AgentIp
     * 
     * @param agentIp
     * @return
     */
    @Override
    public int updateByPrimaryKey(AgentIpPojo agentIp) {
        return agentIpMapper.updateByPrimaryKey(agentIp);
    }

    /**
     * 根据ip更新AgentIp
     * 
     * @param agentIp
     * @return
     */
    @Override
    public int updateByIpSelective(AgentIpPojo agentIp) {
        return agentIpMapper.updateByIpSelective(agentIp);
    }

	@Override
	public int updateAgentByIps(String agentIps, String aliasNames, String removeDiskPartitions) {
		int num = 0;
		if (StringUtils.isNotEmpty(agentIps)) {
			String[] ipArray = agentIps.split(",");
			String[] aliasNameArr = aliasNames.split(",");
			String[] removeDiskPartitionArr = removeDiskPartitions.split(",");

			for (int i = 0; i < ipArray.length; i++) {
				AgentIpPojo agentIp = new AgentIpPojo();
				agentIp.setAgentIp(ipArray[i]);

				String aliasName = aliasNameArr[i];
				if (StringUtils.isEmpty(aliasName) || Objects.equals(aliasName, "null")) {
					agentIp.setAliasName(Constants.EMPTY_STRING);
				} else {
					agentIp.setAliasName(aliasName);
				}

				String removeDiskPartition = removeDiskPartitionArr[i];
				if (StringUtils.isEmpty(removeDiskPartition) || Objects.equals(removeDiskPartition, "null")) {
					agentIp.setRemoveDiskPartition(Constants.EMPTY_STRING);
				} else {
					agentIp.setRemoveDiskPartition(removeDiskPartition);
				}
				agentIp.setUpdateBy(SecurityUtils.getUser().getName());
				agentIp.setUpdateTime(new Date());
				num = agentIpMapper.updateByIpSelective(agentIp);
				if (num == 0) {
					return num;
				}

				Map<String, AgentIpPojo> agentIpMap = AgentConfigManager.agentIpMap;
				AgentIpPojo po = agentIpMap.get(agentIp.getAgentIp());
				if (po != null) {
					po.setAliasName(agentIp.getAliasName());
					po.setRemoveDiskPartition(agentIp.getRemoveDiskPartition());
				}
			}
		}

		return num;
	}

	/**
     * 根据ip更新状态为逻辑删除
     * 
     * @param ipArray
     * @return
     */
    @Override
    public void updateStatusByIp(String[] ipArray) {
        agentIpMapper.updateStatusByAgentIp(ipArray);

        // 删除成功后，移除
        for (String ip : ipArray) {
            CopyOnWriteArraySet<String> ipSet = AgentConfigManager.ipSet;
            if (ipSet.contains(ip)) {
                ipSet.remove(ip);
            }

            Map<String, AgentIpPojo> agentIpMap = AgentConfigManager.agentIpMap;
            AgentIpPojo po = agentIpMap.get(ip);
            if (po != null) {
                po.setStatus(1);
            }
        }
    }

    /**
     * 统计正常的agentip个数
     * 
     * @return
     */
    @Override
    public int countNormalAgentIp() {
        return agentIpMapper.countNormalAgentIp();
    }

    /**
     * 批量删除agent ip
     * @param ips
     * @return
     */
	@Override
	public R deleteAgentByIps(String[] ips) {
        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < ips.length; i++) {
            if (i != 0) {
                sb.append(",");
            }
            sb.append("'");
            sb.append(ips[i]);
            sb.append("'");
        }

        // 不允许删除最近十分钟内有采集数据的Agent
        Date beforeMinute = DateTool.getBeforeMinute(new Date(), 10);

        String tableName = "conf_agent_status_info";
        Map<String, String> map = new HashMap<>();
        map.put("tableName", tableName);
        map.put("ips", sb.toString());

        SimpleDateFormat sdf = new SimpleDateFormat(Constants.YYYY_MM_DD_HH_MM_SS);
        map.put("startTime", "'" + sdf.format(beforeMinute) + "'");
        List<AgentStatusInfoVo> voList = agentStatusInfoService.countTenMinuteGroupByIp(map);
        if (!CollectionUtils.isEmpty(voList)) {
            sb = new StringBuffer();
            int i = 0;
            for (AgentStatusInfoVo vo : voList) {
                if (i != 0) {
                    sb.append(",");
                }
                sb.append(vo.getAgentIp());
                i++;
            }
            return R.failed(null,"不允许删除最近十分钟内有采集数据的Agent：" + sb.toString());
        }
        updateStatusByIp(ips);
        
        return R.ok();
	}
    
    
}
